<?php


namespace app\api\services;

use app\common\libs\Singleton;
use app\common\models\Order\OrderPay;
use app\common\models\Order\ServiceOrder;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;

class ServiceTeamService
{
    use Singleton;

    /**
     * 支付成功
     * @param $orderNo
     * @param string $tradeNo
     * @return bool
     */
    public function payCallback($orderNo, string $tradeNo = ''): bool
    {
        $date = date('Y-m-d H:i:s');
        $orderDate = ['status' => 2, 'pay_at' => $date, 'trade_no' => $tradeNo];
        try {
            $where = [
                'order_no' => $orderNo,
                'status' => 1
            ];
            ServiceOrder::getInstance()->where($where)->update($orderDate);


        } catch (\Exception $e) {
            return false;
        }
        return true;
    }

    /**
     * @param $uid
     * @param $order
     * @param $payType
     * @return array|false|string
     */
    public function payOrder($uid, $order, $payType)
    {
        OrderPay::getInstance()->startTrans();
        try {

            $data = [
                'pay_price' => $order['price'],
            ];
            $ret = ServiceOrder::getInstance()->where('id', $order['id'])->update($data);
            if (!$ret) {
                return false;
            }

            $data = [
                'user_id' => $uid,
                'pay_amount' => 0,
                'pay_price' => $order['price'] ?? $order['pay_price'],
                'order_no' => $order['orderNo'] ?? $order['order_no'],
                'pay_no' => getNo('STPay'),
                'pay_status' => $payType,
                'expire_at' => date('Y-m-d H:i:s', strtotime('+15 minute'))
            ];
            $ret = OrderPay::getInstance()->insert($data);
            if (!$ret) {
                OrderPay::getInstance()->rollback();
                return false;
            }
        } catch (\Exception $e) {
            OrderPay::getInstance()->rollback();
            return $e->getMessage();
        }

        return $data;
    }

    /**
     * @param $orderNo
     * @return array
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function getServiceOrder($orderNo): array
    {
        $where = [
            ['order_no', '=', $orderNo],
            ['expire_at', '>', date('Y-m-d H:i:s')],
        ];
        $info = ServiceOrder::getInstance()->where($where)->find();
        return empty($info) ? [] : $info->toArray();
    }
}